﻿using Devonline.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;

namespace Devonline.AspNetCore.OData;

/// <summary>
/// 基于 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext"></typeparam>
/// <typeparam name="TEntitySet"></typeparam>
/// <typeparam name="TKey"></typeparam>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public abstract class ODataServiceController<TDbContext, TEntitySet, TKey> : DataServiceController<TDbContext, TEntitySet, TKey> where TDbContext : DbContext where TEntitySet : class, IEntitySet<TKey> where TKey : IConvertible
{
    public ODataServiceController(IDataService<TDbContext, TEntitySet, TKey> dataService) : base(dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public IActionResult Get() => Ok(_dataService.GetQueryable());
}

/// <summary>
/// 基于字符串作为主键的 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext"></typeparam>
/// <typeparam name="TEntitySet"></typeparam>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public abstract class ODataServiceController<TDbContext, TEntitySet> : DataServiceController<TDbContext, TEntitySet> where TDbContext : DbContext where TEntitySet : class, IEntitySet
{
    public ODataServiceController(IDataService<TDbContext, TEntitySet> dataService) : base(dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public IActionResult Get() => Ok(_dataService.GetQueryable());
}